package com.example.ch02_student.adminsDo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.ch02_student.R;
import com.example.ch02_student.entity.Teacher;
import com.example.ch02_student.utils.ResultVo;
import com.example.ch02_student.utils.UrlBase;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddTeacherInfo extends AppCompatActivity {
private EditText no,name,sex1,age1,tel1,email1;
private OkHttpClient okHttpClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_teacher_info);
        //初始化控件
        init();
        okHttpClient=new OkHttpClient();
    }



    public void addTeacherInfo(View view){
        String tno = no.getText().toString();
        String tname=name.getText()+ "";
        String sex=sex1.getText()+ "";
        Integer age=0;
    if (age1.getText()!=null&&!"".equals(age1.getText().toString())){
         age=Integer.parseInt(age1.getText()+ "");
    }

        String email = email1.getText().toString();
        String tel=tel1.getText()+ "";
        //
        Teacher teacher = new Teacher(tno, tname, "img", sex, age, tel, null);
        String s = new Gson().toJson(teacher);
        final RequestBody requestBody = RequestBody.create(s, MediaType.parse("application/json"));
        //发送请求
        Request build = new Request.Builder()
                .url(UrlBase.URL_BASE + "/teacher/addTeacher?email=" + email)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(build);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                ResultVo resultVo = new Gson().fromJson(response.body().string(), ResultVo.class);
                if (resultVo.getCode()==1000){
                    System.err.println("success");
                }else {
                    Looper.prepare();
                    Toast.makeText(AddTeacherInfo.this,"id重复",Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }
        });


    }
    //初始化控件
    public void init(){
    no=findViewById(R.id.no);
    name=findViewById(R.id.name);
    sex1=findViewById(R.id.sex);
    age1=findViewById(R.id.age);
    tel1=findViewById(R.id.tel);
    email1=findViewById(R.id.email);
    }
}
